#!/bin/bash 

. /etc/default/owfs 

PANEL_SENSOR=28.D23974010000
#TANK_SENSOR=28.B70674010000
TANK_SENSOR=28.850874010000
TANK_TOP_SENSOR=10.AEEA89010800

TEMPSTART=20
TEMPSTOP=10

OVERHEAT=80

function pump ()
{
  case $1 in 
    on)
      echo "0" > /sys/bus/i2c/devices/0-0038/write
      echo "Pump On"
      ;;
    off)
      echo "255" > /sys/bus/i2c/devices/0-0038/write
      echo "Pump Off"
      ;;
   esac
}

function higher ()
{
  # returns 1 if $1+tempdiff> $2, otherwise returns zero. * status is $1<$2
  case `echo "a=$1;b=$2;d=$3;r=-1;if(a-d<=b)r=0;if(a-d>b)r=1;r"|bc` in
    0) return 0
    ;; 
    1) return 1
    ;; 
    *) return 0
    ;; 
  esac
}


while true
do
  owdir ${CLIENT_OPTS} > /dev/null
  sleep 20
  PANEL_TMP=`owread ${CLIENT_OPTS} $PANEL_SENSOR/fasttemp`
  PANEL_TMP=${PANEL_TMP#"${PANEL_TMP%%[! ]*}"}
  TANK_TMP=`owread ${CLIENT_OPTS} $TANK_SENSOR/fasttemp`
  TANK_TMP=${TANK_TMP#"${TANK_TMP%%[! ]*}"} 
  TANKTOP_TMP=`owread ${CLIENT_OPTS} $TANK_TOP_SENSOR/temperature`
  TANKTOP_TMP=${TANKTOP_TMP#"${TANKTOP_TMP%%[! ]*}"} 
  higher $PANEL_TMP $TANK_TMP $TEMPSTART
  RET1=$?
  higher $PANEL_TMP $TANK_TMP $TEMPSTOP
  RET2=$?
  higher $TANKTOP_TMP $OVERHEAT 0
  RET3=$?
  higher $PANEL_TMP $TANKTOP_TMP 4
  RET4=$?
  if [ "RET3" = "1" ]; then 
    pump off; #Overheat status - let it stagnate
    PUMP=0
  else
    # normal operation
    if [ "$RET1" = "1" ]; then pump on; PUMP=1; fi 
    if [ "$RET4" = "1" ]; then pump on; PUMP=1; fi 
    if [ ! "$RET2" = "1" ]; then pump off; PUMP=0; fi
  fi
  rrdtool update /var/log/solar.rrd N:$PANEL_TMP:$TANKTOP_TMP:$TANK_TMP:$PUMP
  echo "Panel:$PANEL_TMP  Tank Base:$TANK_TMP  Tank:$TANKTOP_TMP"
#  pbmtext "$TANKTOP_TMP" | pnmscalefixed 10 | ppmtofb -s 
done